package com.module.circle.ui.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.*
import androidx.core.content.ContextCompat
import com.common.app.data.bean.circle.CircleDetailMemberListBean
import com.common.app.data.bean.circle.CirclesClickLikeModel
import com.common.app.data.bean.circle.CirclesMedalModel
import com.common.app.data.repository.CircleApi
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.getShowMsg
import com.common.base.app.extras.loadRound
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.common.base.data.ListCommon
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getColor
import com.module.circle.R
import com.module.circle.databinding.CircleMemberInfoDialogBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/08/12
 *
 * 描述：成员信息弹框
 *
 * 修订历史：
 *
 */
class MemberInfoDialog(
    private var mContext: Context,
) :
    Dialog(mContext, R.style.custom_dialog_sv), View.OnClickListener {
    private val binding by lazy { CircleMemberInfoDialogBinding.inflate(LayoutInflater.from(context)) }

    var scope = CoroutineScope(Dispatchers.IO)

    private var mBean:CircleDetailMemberListBean? = null

    private val mAdapter by lazy { MedalInfoListAdapter() }

    /**
     * 点击监听
     */
    private var listener: OnMemberInfoDialogListener? = null

    init {
//        setCanceledOnTouchOutside(false)
//        setDialogTheme()
    }

    /**
     * set dialog theme(设置对话框主题)
     */
    private fun setDialogTheme() {
        requestWindowFeature(Window.FEATURE_NO_TITLE) // android:windowNoTitle
        window?.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) // android:backgroundDimEnabled默认是true的
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) // android:windowBackground
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.dialogRoot.setOnClickListener(this)
        binding.tvLikeBtn.setOnClickListener(onClick = this)

        binding.hrv.apply {
            adapter = mAdapter
        }
    }

    override fun onClick(view: View) {
        when (view) {
            binding.dialogRoot -> {}
            binding.tvLikeBtn->requestClickLike()
        }

    }

    override fun show() {
        super.show()
        window?.apply {
            //设置宽度
            attributes.width = ViewGroup.LayoutParams.MATCH_PARENT
            attributes.gravity = Gravity.BOTTOM //设置dialog 在布局中的位置
            setWindowAnimations(R.style.bottom_style_dialog) //添加动画:
            setBackgroundDrawable(ColorDrawable(mContext.getColor(R.color.transparent))) // android:windowBackground
        }
    }

    fun show(data: CircleDetailMemberListBean) {
        show()
        mBean = data
        mBean?.let {
            binding.ivCover.loadRound(it.avatar_url, 100)
            binding.tvName.text = it.nickname

            ViewUtils.setVisible(binding.tvIntroduction, !it.description.isNullOrEmpty())
            binding.tvIntroduction.text = it.description

            ViewUtils.setVisible(binding.imgSex, it.sex < 0)
            binding.imgSex.setImageDrawable(when(it.sex){
                0-> ViewUtils.getDrawable(R.drawable.circle_circle_sex_female_icon)
                1-> ViewUtils.getDrawable(R.drawable.circle_circle_sex_male_icon)
                else-> null
            })

            binding.tvMedalNum.text = "${it.badge_count}${
                ViewUtils.getString(R.string.circle_splicing_medal_hint
                )
            }"

            binding.tvLikeNum.text = it.like_count.toString()
            setLikeBtnUI(it.is_liked)
            getMedalList()
        }
    }

    private fun setLikeBtnUI(isLike:Boolean){
        isLike.yes {
            binding.tvLikeBtn.setText(R.string.common_like_hint2)
            binding.tvLikeBtn.setTextColor(getColor(R.color.c_7f7f7f))
            binding.tvLikeBtn.background = ContextCompat.getDrawable(mContext, R.drawable.bg_stroke_round_d9d9d9_100)
        }.otherwise {
            binding.tvLikeBtn.setText(R.string.common_like_hint)
            binding.tvLikeBtn.setTextColor(getColor(R.color.white))
            binding.tvLikeBtn.background = ContextCompat.getDrawable(mContext, R.drawable.btn_selector_product_100)
        }
    }


    /**
     * @param listener
     */
    fun setListener(listener: OnMemberInfoDialogListener?) {
        this.listener = listener
    }

    /**
     *
     */
    interface OnMemberInfoDialogListener {
        fun onMemberInfoChange(mId:Int, isLike:Boolean,likeCount:Long)
    }



    private fun getMedalList() {
        if (mBean == null){
            showToast(R.string.common_error_tip)
            return
        }
        scope.launch {
            RxHttp.postJson(CircleApi.MEDAL_LIST)
                .add("user_id", mBean?.user_id)
                .toFlow<ListCommon<CirclesMedalModel>>()
                .catch { e ->
                }.collect { dataIt->
                    dataIt.isSuccess().yes {
                        dataIt.Data?.let { listIt->
                            val listTemp = listIt.filter { it.current_level >= 1 }
                            doOnUiThread {
                                mAdapter.setList(listTemp)
                            }
                        }
                    }
                }
        }
    }


    private fun requestClickLike() {
        if (mBean == null){
            showToast(R.string.common_error_tip)
            return
        }
        scope.launch {
            RxHttp.postJson(CircleApi.CLICK_LIKE)
                .add("target_user_id", mBean?.user_id)
                .toFlow<CommonBean<CirclesClickLikeModel>>()
                .catch { e ->
                    showToast(e.getShowMsg())
                }.collect { responseIt->
                    responseIt.isSuccess().yes {
                        responseIt.Data?.let { dataIt->
                            doOnUiThread {
                                setLikeBtnUI(dataIt.is_liked)
                                binding.tvLikeNum.text = dataIt.like_count.toString()
                            }
                            listener?.onMemberInfoChange(mBean?.user_id?:0,dataIt.is_liked,dataIt.like_count)
                        }
                    }
                }
        }
    }
}
